package com.hziee.graduate.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hziee.graduate.ticket.dao.OrderDao;
import com.hziee.graduate.ticket.dao.ScheduleDao;
import com.hziee.graduate.ticket.dao.SeatScheduleDao;
import com.hziee.graduate.ticket.dao.TicketsDao;
import com.hziee.graduate.ticket.dto.R;
import com.hziee.graduate.ticket.entity.*;
import com.hziee.graduate.ticket.service.TicketsService;
import com.hziee.graduate.ticket.utils.OrderUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.krb5.internal.Ticket;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service("ticketsService")
public class TicketsServiceImpl extends ServiceImpl<TicketsDao, Tickets> implements TicketsService {

    @Resource
    private TicketsDao ticketsDao;

    @Resource
    private OrderDao orderDao;

    @Resource
    private ScheduleDao scheduleDao;

    @Resource
    private SeatScheduleDao seatScheduleDao;

    @Override
    @Transactional
    public R<Tickets> addTicket(Tickets ticket) {
        Long userId = ticket.getUserId();
        String orderId = ticket.getOrderId();
        if(orderId.equals("-1")) {
            // 生成订单
            String orderCode = OrderUtil.getOrderCode(userId);
            Order order = new Order();
            order.setOrderId(orderCode);
            order.setUserId(userId);
            order.setCreateTime(LocalDateTime.now());
            int insert = orderDao.insert(order);
            //插入电影票
            ticket.setOrderId(order.getOrderId());
            ticketsDao.insert(ticket);
        }else{
            // 如果是已经有订单了,那么就插入电影票
            Order order = orderDao.selectOne(new QueryWrapper<Order>().eq("order_id",orderId));
            if(order == null){
                Order oldOrder = new Order();
                oldOrder.setOrderId(orderId);
                oldOrder.setUserId(userId);
                oldOrder.setCreateTime(LocalDateTime.now());
                int insert = orderDao.insert(oldOrder);
            }
            ticket.setOrderId(orderId);
            ticketsDao.insert(ticket);
        }
        // 占用座位
        SeatSchedule seatSchedule = new SeatSchedule();
        seatSchedule.setSeatStatus(0);
        HashMap<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("room_id", ticket.getRoomId());
        queryMap.put("row_id", ticket.getSeatRow());
        queryMap.put("col_id", ticket.getSeatCol());
        queryMap.put("schedule_id", ticket.getScheduleId());
        UpdateWrapper<SeatSchedule> seatUpdateWrapper = new UpdateWrapper<SeatSchedule>().allEq(queryMap);
        int update = seatScheduleDao.update(seatSchedule, seatUpdateWrapper);
        return R.success(ticket);
    }

    @Override
    public R<List<Ticket>> getTicketByOrder(String orderId) {
        if(orderId.equals("-1")) {
            return R.success(new ArrayList<Ticket>());
        }else {
            List<Tickets> ticketByOrder = query().eq("order_id",orderId).list();
            return R.success(ticketByOrder);
        }
    }

    @Override
    @Transactional
    public R<Object> removeTicket(Tickets ticket) {
        // 查找订单下面的电影票数量
        Integer ticketNum = query().eq("order_id", ticket.getOrderId()).count();
        if(ticketNum == 1) {
            orderDao.delete(new QueryWrapper<Order>().eq("order_id",ticket.getOrderId()));
        }
        remove(new QueryWrapper<Tickets>().eq("ticket_id",ticket.getTicketId()));
        // 如果等于1说明删除的电影票是该订单的最后一张票，应该连同订单一同删除
        SeatSchedule seatSchedule = new SeatSchedule();
        seatSchedule.setSeatStatus(1);
        HashMap<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("room_id", ticket.getRoomId());
        queryMap.put("row_id", ticket.getSeatRow());
        queryMap.put("col_id", ticket.getSeatCol());
        queryMap.put("schedule_id", ticket.getScheduleId());
        UpdateWrapper<SeatSchedule> seatUpdateWrapper = new UpdateWrapper<SeatSchedule>().allEq(queryMap);
        int update = seatScheduleDao.update(seatSchedule, seatUpdateWrapper);
        return R.success();
    }

    @Override
    public R<Object> checkTicket(Long ticketId) {
         boolean update = update().set("check_status", 1).eq("ticket_id", ticketId).update();
         return R.success();
    }

    @Override
    public R<Integer> getTicketStatus(Long ticketId) {
        // 检查这张票是否被检过了，如果被检过了就跳转到评价页面
        Tickets ticketById = ticketsDao.selectOne(new  QueryWrapper<Tickets>().eq("ticket_id", ticketId));
        // 获取这张票的排班的时间
        Schedule scheduleById = scheduleDao.selectOne(new QueryWrapper<Schedule>().eq("schedule_id", ticketById.getScheduleId()));
        if(ticketById.getCheckStatus() == 1) {
            // 票已经被检过了
            return R.success(ticketById);
        }
        // 没有检测过但是过了时间
        String date = scheduleById.getDate();
        Integer end = scheduleById.getEnd();
        // 将Date转为LocalDateTime
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将字符串转化为日期
        DecimalFormat decimalFormat = new DecimalFormat("00.#");
        Date now = new Date();
        Date endTime = null;
        try {
            endTime = sdf.parse(date + " " + decimalFormat.format(end/60) + ":" + decimalFormat.format(end%60) + ":00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        boolean after = now.after(endTime);
        if(after) {
//            boolean update = update().set("check_status", 1).eq("ticket_id", ticketId).update();
            return R.error("该票已经过期了",scheduleById.getMovieId());
        };
        // 如果没有被检过说明可以进行更新,什么也不做
        return R.success(ticketById);
    }
}

